// 附件的数据模型

package misc

import (
	//"fmt"
	"errors"
	"strings"
	"time"
	"dhfshop/models"
	"dhfshop/models/consts"
	//"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
)

func init() {
	orm.RegisterModel(new(AttachType), new(Attachment))
}

type AttachType struct {
	TypeId       int64     `orm:"column(type_id);auto;pk" json:"type_id" form:"type_id"`
	CompanyId    int64     `orm:"column(company_id)" json:"company_id" form:"-"`
	Name         string    `orm:"column(name)" json:"name" form:"name"`
	Remark       string    `orm:"column(remark)" json:"remark" form:"remark"`
	CreatedAt    time.Time `orm:"column(created_at);auto_now_add;type(datetime)" json:"-"`
	CreatedAtStr string    `orm:"-" json:"created_at"`
	UpdatedAt    time.Time `orm:"column(updated_at);auto_now;type(datetime)" json:"updated_at"`
}

type Attachment struct {
	Id           int64      `orm:"column(id);auto;pk" json:"id"`               //附件自增Id
	CompanyId    int64      `orm:"column(company_id)" json:"company_id"`
	ParentId     string     `orm:"column(parent_id);size(190);index" json:"parent_id"`   // 文件的父ID
	CategoryId   int64      `orm:"column(categoryId)" json:"categoryId"`
	CreatorId    int64      `orm:"column(creator_id)" json:"creator_id"`
	UUId         string     `orm:"column(uuid);size(36)" json:"uuid"`            //附件的uuid
	OriginalName string     `orm:"column(original_name)" json:"original_name"`
	URL          string     `orm:"column(url)" json:"url"`
	Size         uint64     `orm:"column(size)" json:"size"`
	Mime         string     `orm:"column(mime);null" json:"mime"`
	Md5Hash      string     `orm:"column(md5_hash);size(190);index" json:"md5_hash"`
	CreatedAt    time.Time  `orm:"column(created_at);auto_now_add;type(datetime)" json:"-"`
	CreatedAtStr string     `orm:"-" json:"created_at"`
	UpdatedAt    time.Time  `orm:"column(updated_at);auto_now;type(datetime)" json:"updated_at"`
}

func CreateAttachment(attachment *Attachment) (id int64, err error) {
	o := models.GetDefaultDB()
	id, err = o.Insert(attachment)
	return
}

func CheckAttachHashExist(creatorId int64,md5Hash string) bool {
	o := models.GetDefaultDB()
	exist := o.QueryTable(new(Attachment)).Filter("creator_id", creatorId).Filter("md5_hash", md5Hash).Exist()
	return exist
}

func GetAttachment(id int64) (attachment *Attachment, err error) {
	o := models.GetDefaultDB()
	attachment = &Attachment{Id: id}
	if err = o.Read(attachment); err != nil {
		return
	}
	/*
	attachment.URL = fmt.Sprintf(
		"http://%s.%s/%s", beego.AppConfig.String("OSSBucketName"), beego.AppConfig.String("OSSHost"), attachment.Name)
	*/
	return
}

func GetAttachmentByUuid(uuid string) (attachment *Attachment, err error) {
	o := models.GetDefaultDB()
	attachment = &Attachment{UUId: uuid}
	if err = o.Read(attachment, "UUId"); err != nil {
		return
	}
	return
}

func GetAttachByMd5Hash(md5Hash string) (attachment *Attachment, err error) {
	o := models.GetDefaultDB()
	attachment = &Attachment{Md5Hash:md5Hash}   //多个的话,read中需要指明列
	if err = o.Read(attachment,"Md5Hash"); err != nil {
		return attachment, err
	}
	return attachment, nil
}

func GetAllAttachments(start,end,mime string,query map[string]string,fields []string,order_by map[string]string,offset int,limit int)([]*Attachment, int64,error) {
	o := models.GetDefaultDB()
	qs := o.QueryTable(new(Attachment))
	if len(start) == 19 {
	    if start_time, err := time.Parse(consts.DATETIME_FORMAT,start); err == nil {
		    qs = qs.Filter("created_at__gte", start_time)
		}
	}
	if len(end) == 19 {
	   if end_time, err := time.Parse(consts.DATETIME_FORMAT,end); err == nil {
	        qs = qs.Filter("created_at__lte", end_time)
	   }
	}
	if len(mime) > 0 {
	   qs = qs.Filter("mime__in", strings.Split(mime, ","))
	}
	for k, v := range query {
		k = strings.Replace(k, ".", "__", -1)
		if ok := strings.Contains(v, "|"); ok {
		    valueArr := strings.Split(v, "|")
			qs = qs.Filter(k, valueArr)
		}else{
		    qs = qs.Filter(k, v)
		}	
	}
	cnt, err := qs.Count()
	var sortFields []string
	for k, v := range order_by {
		orderby := ""
		if v == "desc" {
			orderby = "-" + k
		} else if v == "asc" {
			orderby = k
		} else {
			return nil, 0, errors.New("Error: Invalid order. Must be either [asc|desc]")
		}
		sortFields = append(sortFields, orderby)
	}
	qs = qs.OrderBy(sortFields...)
	var lists []*Attachment
	if _, err = qs.Limit(limit, offset).All(&lists, fields...); err == nil {
		return lists, cnt, nil
	}
	return nil, 0, err
}


func UpdateAttachment(attachment *Attachment, fields ...string) error {
	o := models.GetDefaultDB()
	a := Attachment{Id: attachment.Id}
	if err := o.Read(&a); err != nil {
		return err
	}
	_, err := o.Update(attachment, fields...)
	return err
}

func DeleteAttachment(id int64) (err error) {
	o := models.GetDefaultDB()
	v := Attachment{Id: id}
	if err = o.Read(&v); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}

func DeleteAttachmentByUuid(uuid string) (err error) {
	o := models.GetDefaultDB()
	v := Attachment{UUId: uuid}
	if err = o.Read(&v, "UUId"); err == nil {
		if _, err = o.Delete(&v); err == nil {
			return nil
		}
	}
	return
}

